<?php

namespace api\controller;

use common\controller\VerifyController;
use common\service\CrontabService;
use support\ErrorCode;
use think\Request;

class CrontabController extends VerifyController
{


    protected $crontabToken = "YmCFffmQq8yw0URs";

    /**
     * @var CrontabService
     */
    private $crontabService;

    public function __construct()
    {
        parent::__construct();
        $this->crontabService = new CrontabService();
    }

    /**
     * 检测用户登录状态
     */
    public function _initialize()
    {
        // 验证请求数据
        $this->checkToken();
    }


    /**
     * 检查是否token正确
     */
    private function checkToken()
    {
        $param = \request()->param();
        if (!array_key_exists('token', $param)) {
            throw_strack_exception("missing crontab token.", ErrorCode::CRONTAB_TOKEN_NOT_EXIST);
        }

        if ($param['token'] != $this->crontabToken) {
            throw_strack_exception("crontab token invalid.", ErrorCode::CRONTAB_TOKEN_INVALID);
        }
    }

    /**
     * 任务逾期 预警检测
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function checkTaskStatus(Request $request)
    {
        $res = $this->crontabService->checkTaskStatus();
        return json(success_response("OK", $res));
    }

    /**
     * 合同过期检查
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function checkContractDate(Request $request)
    {
        $res = $this->crontabService->checkContractDate();
        return json(success_response("OK", $res));
    }

    /**
     * 检查并删除重复生成的任务
     * @param Request $request
     */
    public function checkRepeatTask(Request $request): \think\Response
    {
        $res = $this->crontabService->checkRepeatTask($request->param()['param']);
        return json(success_response("OK", $res));
    }

    /**
     * 前置模块数据修复
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function fixEntityPreModuleData(Request $request)
    {
        if ($request->param()['module_code'] === 'asset' || $request->param()['module_code'] === 'level') {
            $res = $this->crontabService->fixAssetPreModuleData($request->param()['param'], $request->param()['module_code']);
        } else if ($request->param()['module_code'] === 'shot') {
            $res = $this->crontabService->fixShotPreModuleData($request->param()['param']);
        } else {
            $res = [];
        }
        return json(success_response("OK", $res));
    }

    /**
     * 检查逾期实体任务
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function checkOverdueEntityTask(Request $request)
    {
        $param = $request->param()['param'];
        $res = $this->crontabService->checkOverdueEntityTask($param['filter']);
        return json(success_response('Ok', $res));
    }
}